import intl from 'react-intl-universal';
import cookie from './cookie';
export const Locale_zh_CN = 'zh-CN';
export const Locale_en_US = 'en-US';
export const Locales = [Locale_zh_CN, Locale_en_US];
export const LocalName = 'culture';

/*
 * 获取语言环境
 *@params:
 *@returns: 返回当前语言环境
 */
export const getLocale = (defaultLocale = Locale_zh_CN, localName = LocalName) => {
  //判斷父容器国际化设置
  const containerlocale = window.top.localStorage.getItem(localName);

  let localeName = defaultLocale;

  if (containerlocale && Locales.includes(containerlocale)) {
    localeName = containerlocale;
  } else {
    //根据URL 、cookie 、localStorage、浏览器 顺序获取设置
    let urlLocale = intl.getLocaleFromURL({ urlLocaleKey: localName });
    let cookieLocale = intl.getLocaleFromCookie({ cookieLocaleKey: localName });
    let localStorageLocale = intl.getLocaleFromLocalStorage({
      localStorageLocaleKey: localName,
    });
    let currentLocale = urlLocale || cookieLocale || localStorageLocale;

    if (currentLocale && Locales.includes(currentLocale)) {
      localeName = currentLocale;

      //设置localStorage,便于内部路由跳转时获取到环境语言
      if (localStorageLocale !== currentLocale) {
        window.localStorage.setItem(localName, currentLocale);
      }
    }
  }

  return localeName;
};
/*
 * 获取语言环境
 *@params:
 *@returns: 返回当前语言cookie环境
 */
export const getCookieLocale = (defaultLocale = Locale_zh_CN, localName = LocalName) => {
  let localeName = defaultLocale;
  let cookieLocale = intl.getLocaleFromCookie({ cookieLocaleKey: localName });
  let currentLocale = cookieLocale || localeName;
  if (Locales.includes(currentLocale)) {
    cookie.set(LocalName, currentLocale);
    return currentLocale;
  } else {
    return localeName;
  }
};

/*
 * 设置语言环境
 *@params:
 *@returns: 设置当前语言cookie环境
 */
export const setCookieLocale = locale => {
  if (Locales.includes(locale)) {
    cookie.set(LocalName, locale);
    return true;
  } else {
    return false;
  }
};
